import React, {Component} from "react";
import {Collapse} from "antd";
import {connect, ConnectProps} from 'umi';
import styles from "./index.less";
import CardBasic from './CardBasic';
import {ChannelContext} from '../TabsBasic/channel-context'
import {ProductInfoType} from './data.d';
import {ProductDataState} from "@/pages/ProductPage/CollapseAccordion/model";

const {Panel} = Collapse;


// 继承ConnectProps，获取其属性，如dispatch，location，history，route
interface PageProps extends ConnectProps {
  products: ProductInfoType[];
  productsLoading: boolean;
  ext: string;
}

// Component<PageProps>是一个react Component组件， 设置props值的类型为PageProps
class CollapseAccordion extends Component<PageProps> {
  // 声明周期函数：组件加载完毕后会执行
  componentDidMount() {
    const {dispatch} = this.props;

    const globalChannel = this.context;
    if (dispatch) {
      dispatch({
        type: 'productWorkplace/getProducts',
        params: {
          distributor: globalChannel,
        },
      });
    }
  }

  render() {
    const {products} = this.props;
    return (
      <div className={styles.container}>
        <div id="components-collapse-demo-accordion">
          <Collapse accordion>
            {
              products.map((item, index) => (
                <Panel header={item.category} key={index}>
                  <CardBasic distributor={this.context} category={item.category}/>
                </Panel>
              ))
            }
          </Collapse>
        </div>
      </div>
    );
  }
}
// 能使用 this.context 来消费最近 Context 上的那个值。你可以在任何生命周期中访问到它，包括 render 函数中。
CollapseAccordion.contextType = ChannelContext;

const mapStateToProps = ({
                           productWorkplace: state,
                           loading
                         }: {
  productWorkplace: ProductDataState;
  loading: {
    effects: {
      [key: string]: boolean;
    };
  };
}) => ({
  // 这里的返回内容会绑定到CollapseAccordion 的 this.props属性上
  ...state,
  // 判断方法是否执行完毕
  productsLoading: loading.effects['productWorkplace/getProducts'],
  ext: "扩展内容"
});
// 第一个参数是名称空间, 第二个参数是dispatchProps, 第三个参数是自定义prop
// ：冒号后面是要返回给this.props的值类型
// connect 绑定数据到组件。
export default connect(mapStateToProps)(CollapseAccordion);
